#!/usr/bin/env python
# -*- coding: UTF-8 -*-

#from ..milonpy import  NMdb

#from . BeautifulSoup import BeautifulSoup 
from  BeautifulSoup import BeautifulSoup
# BeautifulSoup   
def str_clear(obj):
    if isinstance(obj, basestring):
        return obj.replace('\n','').replace('\t','').replace('\r','').strip()
    else:
        return obj
             
class dictList(list):
    """a minimal pseudo dictionary based on list of lists where lists[0] are keys - helps coz dict is not orderedl""" 
    def getCol(self,key,row): 
        idx=self[0].index(key)
        return self[row][idx]   
    def setCol(self,key,row, val):
        idx=self[0].index(key)
        self[row][idx]=val
        return self[row][idx]    
    def keys(self):
        return self[0]
    def values(self, row):
        return self[row]
 
 
def TableRowsToList(table, clearNPC=False):
    if isinstance(table, basestring):table= BeautifulSoup(table)
    def scrapRowVals(row):
        rt= [cell for cell in row.findAll("td")] 
        rt= [cell.findAll(text=True) for cell in rt] 
        if clearNPC:rt=[str_clear(it) for it in rt] 
        return rt       
    return [scrapRowVals(row) for row in table.findAll("tr")]
 
def lst_clear (lst): 
    for item in lst:
        if isinstance(lst, basestring):return str_clear(lst) 
        else:return [lst_clear(item) for item in lst]
 
def lst_UnlistSingleEl (lst): 
    for item in lst:
        if isinstance(item, list): 
            if len(item)==1:return item[0]
            else:
                return lst_UnlistSingleEl(item)
        else:return item 
 
def lst_removeEmptyStrings (lst): 
    for item in lst:
        if isinstance(item, basestring):
            if item=='':lst.remove(item)  
        else: lst_removeEmptyStrings(item)  
def tryEval(s):
    try:return eval(s)
    except:return(s)    
    
def strToDic(st, itemSeparator=';',keySep='='): 
    """ u'Nph = 39; Dmin = 999.9 km; Rmss = 1.26 seconds; Gp = 162 >>> {'Rmss': '1.26 seconds', 'Dmin': u'999.9 km', 'Nph': '39', u'Gp': u'162'} 
    """
    r=st.split(itemSeparator) 
    r=[t.split('=') for t in r] 
    r=lst_clear(r) 
    r=dict (r)
    for k in r.keys():r[k]=tryEval(r[k])
    return r
 
def lst_clearOLD(l, removeBlanks=True):
    for it in l[:]: 
        if isinstance(it, list): 
            if len(it) == 0 :
                l.remove (it) 
            elif len(it)==1: 
                l[l.index(it)]=str_clear(it[0])   
            else:   
                it=lst_clear(it, removeBlanks) 
        else:
            if removeBlanks and it[0].strip()=="":
                l.remove(it) 
            else:l[l.index(it)]=str_clear(it)
    return l
